import os
import json
import httpx
from typing import Any

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("WeatherServer")

OPEN_WEATHER_BASE_URL = "https://api.openweathermap.org/data/2.5/weather"
OPEN_WEATHER_API_KEY = "98cdb20187473b93432b86d818cb070"
OPEN_WEATHER_USER_AGENT = "weather-app/1.0"


async def fetch_weather(city: str) -> dict[str, Any] | None:
    """
    从OpenWeather API获取天气信息。
    :param city: 城市名称（需要使用英文，比如Beijing）
    :return: 返回天气数据字典；若出错则返回包含error信息的字典
    """
    params = {
        "q": city,
        "appid": OPEN_WEATHER_API_KEY,
        "units": "metric",
        "lang": "zh_cn"
    }
    headers = {"User-Agent": OPEN_WEATHER_USER_AGENT}
    async with httpx.AsyncClient as client:
        res = await client.get(OPEN_WEATHER_BASE_URL, params=params, headers=headers, timeout=30.0)
        res.raise_for_status()
        return res.json()


def format_weather(data: dict[str, Any] | str) -> str:
    """
    将天气数据格式化为易读文本
    :param data: 天气数据（可以是字典或json字符串）
    :return: 返回格式化后的天气信息字符串
    """
    # 如果传入的是字符串，则尝试将其解析为字典
    if isinstance(data, str):
        data = json.loads(data)

    # 如果数据中包含错误信息，直接返回错误提示
    if "error" in data:
        return f"获取天气信息时出错：{data['error']}"

    # 提取数据时容错处理
    city = data.get("name", "未知")
    country = data.get("sys", {}).get("country", "未知")
    temp = data.get("main", {}).get("temp", "未知")
    humidity = data.get("main", {}).get("humidity", "未知")
    wind_speed = data.get("wind", {}).get("speed", "未知")
    weather_list = data.get("weather", [{}])
    description = weather_list[0].get("description", "未知")

    return (
        f"{city} {country} 的天气情况如下：\n"
        f"天气：{description}\n"
        f"温度：{temp}°C\n"
        f"湿度：{humidity}%\n"
        f"风速：{wind_speed} m/s"
    )


@mcp.tool()
async def query_weather(city: str) -> str:
    """
    查询指定城市的天气信息，当查询某城市天气时，需要输入对应的英文，比如Beijing、Shanghai
    :param city: 城市名称（需要使用英文，比如Beijing）
    :return: 天气信息字符串
    """
    # data = await fetch_weather(city)
    # return format_weather(data)
    return f"{city}天气不好不坏，还算ok！"


if __name__ == "__main__":
    # 以标准I/O方式运行MCP服务器
    mcp.run(transport="stdio")
